package com.ls.lserp.modules.purchase.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.common.entity.OgnizationEntity;
import com.ls.lserp.modules.purchase.entity.PurchaseRequest;
import com.ls.lserp.modules.purchase.entity.SelPurchaseMaterial;
import com.ls.lserp.modules.purchase.service.PurchaseRequestService;
import com.ls.lserp.modules.purchase.service.SelPurchaseMaterialService;
import com.ls.lserp.modules.setting.entity.Ognization;
import com.ls.lserp.modules.sys.entity.User;
import com.ls.lserp.modules.sys.utils.SequenceUtil;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

@Controller
@RequestMapping(value = "${adminPath}/purchase/request/")
public class PurchaseRequestController extends BaseController {

	
	@Autowired
	private PurchaseRequestService purchaseRequestService;
	@Autowired
	private SelPurchaseMaterialService selPurchaseMaterialService;
	@Autowired
	Configuration freemarkerConfiguration;
	
	@ModelAttribute
	public PurchaseRequest get(@RequestParam(required = false) String id) {

		// 判断id是否为空
		if (StringUtils.isNotBlank(id)) {
			// 执行查询语句 查询基本信息
			return purchaseRequestService.get(Long.parseLong(id));
		} else {
			// 若为空，实例化
			return new PurchaseRequest();
		}
	}

	/**
	 * @Title: 画面跳转用
	 * @return url
	 */
	@RequiresPermissions("purchase:request:view")
	@RequestMapping(value = { "" })
	public String list(Model model) {
		// 画面跳转
		return "modules/purchase/purchaseRequest";
	}

	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param purchaseRequest
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws Exception
	 */
	@RequiresPermissions("purchase:request:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(PurchaseRequest purchaseRequest, HttpServletRequest request, HttpServletResponse response,
			Model model) throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "purchaseRequest");
		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		// 入库申请单
		searchParam.append("&inventoryRequestNo=");
		searchParam.append(purchaseRequest.getInventoryRequestNo());
		// 供货商名称
		searchParam.append("&venderName=");
		searchParam.append(purchaseRequest.getVenderName());
		// 日期
		searchParam.append("&dateFrom=");
		searchParam.append(purchaseRequest.getDateFrom());
		searchParam.append("&dateTo=");
		searchParam.append(purchaseRequest.getDateTo());
		// 状态
		searchParam.append("&tabPageStatus=");
		searchParam.append(purchaseRequest.getTabPageStatus());
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());
		
		// 查询一览页面数据
		Page<PurchaseRequest> page = purchaseRequestService.findList(new Page<PurchaseRequest>(request, response),purchaseRequest);
		// 读取系统路径
		String strUri = request.getContextPath() + Global.getAdminPath();
		// 读取文件生成字符串
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		map.put("adminUri", strUri);
		map.put("purchaseRequests", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
		strHtml = FreeMarkerTemplateUtils
				.processTemplateIntoString(freemarkerConfiguration.getTemplate("purchaseRequest.ftl"), map);
		listMap.put("purchaseRequest", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}
	
	/**
	 * 进入编辑页面
	 * @param purchaseRequest
	 * @param model
	 * @return
	 */
	@RequiresPermissions("purchase:request:edit")
	@RequestMapping(value = "form")
	public String form(PurchaseRequest purchaseRequest,RedirectAttributes redirectAttributes, Model model,HttpSession session) {
		
		// 获取当前用户
		User curLoginUser = purchaseRequest.getCurrentUser();
		
		// 下拉列表客户名称取得
		Ognization paramOgnization = new Ognization();
		//账户类型（1、平台账户；2、店铺账户；3、加工厂账户；4、供货商账户；5、客户；）
		paramOgnization.setOgnizationType(4L);
		paramOgnization.setCurrentUser(curLoginUser);
		purchaseRequest.setVenderList(purchaseRequestService.selVenderList(paramOgnization));
		
		if(purchaseRequest.getId() == null){
			// 入库单条码
			purchaseRequest.setStockBarCode(SequenceUtil.inventoryRequestbarcode().getReturnCode());
			
			// 下拉菜单（自采入库）
			purchaseRequest.setInventoryCategory(ResourcesUtil.getConfig("inventory_category_purchase"));
		}else{
		   	   // 查找入库申请明细
			   List<PurchaseRequest> resultRequestList = purchaseRequestService.findRequestDetailsList(purchaseRequest);
			   purchaseRequest.setRequestDetailsList(resultRequestList);
		}
		
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("purchaseRequest", purchaseRequest);
		
		// 返回页面地址
		return "modules/purchase/purchaseRequestCreate";
	}
    
    /**
     * @Title: delRequestDetail
     * @Description: 删除入库申请明细
     * @param @param inventoryRequest
     * @param @param model
     * @param @param session
     * @param @return
     * @return String 
     * @throws
     */

   @RequiresPermissions("purchase:request:edit")
   @RequestMapping(value = "delRequestDetails")
   public String delRequestDetail(PurchaseRequest purchaseRequest, HttpServletRequest request, HttpServletResponse response, Model model) {
       try {
     	  
    	   purchaseRequest.getRequestDetailsList().remove(purchaseRequest.getTrIndex());
    	   
   	       // 将page值赋值给mvc model层返回jsp页面
      	   model.addAttribute("purchaseRequest", purchaseRequest);
   	    
          // 返回地址
          return "modules/purchase/purchaseRequestCreate";
       } catch (Exception e) {
           // 记录日志
           logger.error(e.getMessage(), e);
           // 返回地址
           return "modules/purchase/purchaseRequestCreate";
       }
   }
   
   /**
    * 保存信息
    * @param purchaseRequest
    * @param request
    * @param model
    * @param response
    * @return
    * @throws ResourceException 
    */
   @RequiresPermissions("purchase:request:edit")
   @RequestMapping(value = "save")
   @ResponseBody
   public String save(PurchaseRequest purchaseRequest, HttpServletRequest request, Model model, HttpServletResponse response , HttpSession session) throws ResourceException {

		// 判断id是否为null （判断新建或修改）
		if(purchaseRequest.getId()!=null){
			// 编辑数据
			// 判断数据是否删除
			PurchaseRequest inventoryRequestNew = get(purchaseRequest.getId().toString());
			// 判断数据是否删除
           if(inventoryRequestNew==null || BaseEntity.DEL_FLAG_DELETE.equals(inventoryRequestNew.getDeleteFlag())){
           	// 返回提示信息
           	return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
           }
			
           // 排他处理
		    if(purchaseRequest.getVersion()==get(purchaseRequest.getId().toString()).getVersion()){
		    	
		    	// 版本号加1
		    	purchaseRequest.setVersion(purchaseRequest.getVersion()+1);
		    }else{
		    	
		    	// 返回提示信息
		        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
		    }
		}
	   
   	   // 保存入库申请
		purchaseRequestService.saveInventoryRequest(purchaseRequest);
   	
   	   // 保存成功返回提示信息
       return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "inventory_request_save_success")));
   }
   
	/**
    * 进入查看页面
    * @param ognization
    * @param model
    * @return
    */
   @RequiresPermissions("purchase:request:view")
   @RequestMapping(value = "show")
   public String show(PurchaseRequest purchaseRequest, Model model) {
	   
   	   // 查找入库申请明细
	   List<PurchaseRequest> resultRequestList = purchaseRequestService.findRequestDetailsList(purchaseRequest);
	   purchaseRequest.setRequestDetailsList(resultRequestList);
   	
       // 将查询结果赋值mvc model层返回jsp页面
       model.addAttribute("purchaseRequest", purchaseRequest);
       
       // 返回页面地址
       return "modules/purchase/purchaseRequestShow";
   }
    
    /**
     * @Title: 2017-04
     * @Description: 添加入库申请明细
     * @param @param addRequestDetails
     * @param @param model
     * @param @param session
     * @param @return
     * @return String 
     * @throws
     */

   @RequiresPermissions("purchase:request:edit")
   @RequestMapping(value = "addRequestDetails")
   public String addRequestDetails(PurchaseRequest purchaseRequest, HttpServletRequest request, HttpServletResponse response, Model model) {
       try {
     	  
   	       // 将page值赋值给mvc model层返回jsp页面
      	   model.addAttribute("purchaseRequest", purchaseRequest);
   	    
          // 返回地址
          return "modules/purchase/purchaseRequestCreate";
       } catch (Exception e) {
           // 记录日志
           logger.error(e.getMessage(), e);
           // 返回地址
           return "modules/purchase/purchaseRequestCreate";
       }
   }
   
   /**
    * @Title: delRequestDetail
    * @Description: 删除入库申请明细
    * @param @param inventoryRequest
    * @param @param model
    * @param @param session
    * @param @return
    * @return String 
    * @throws
    */

  @RequiresPermissions("purchase:request:edit")
  @RequestMapping(value = "delAllDetails")
  public String delAllDetails(PurchaseRequest purchaseRequest, HttpServletRequest request, HttpServletResponse response, Model model) {
      try {
    	  
    	  purchaseRequest.setRequestDetailsList(new ArrayList<PurchaseRequest>());
   	   
  	       // 将page值赋值给mvc model层返回jsp页面
     	   model.addAttribute("purchaseRequest", purchaseRequest);
  	    
         // 返回地址
         return "modules/purchase/purchaseRequestCreate";
      } catch (Exception e) {
          // 记录日志
          logger.error(e.getMessage(), e);
          // 返回地址
          return "modules/purchase/purchaseRequestCreate";
      }
  }
  
	/**
	 * @Title: 画面跳转用
	 * @return url
	 */
	@RequiresPermissions("purchase:request:view")
	@RequestMapping(value = { "materialList" })
	public String materialList(Model model,SelPurchaseMaterial selPurchaseMaterial) {
		// 客户list
		List<OgnizationEntity> ogizationList = selPurchaseMaterialService.getOgizationList();
		model.addAttribute("ogizationList",ogizationList);
		
//		// 采购合同list
//		List<SelPurchaseMaterial> contractMaterialNoList = selPurchaseMaterialService.getContractMeterialNoList(selPurchaseMaterial);
//		model.addAttribute("contractMaterialNoList",contractMaterialNoList);

		// 它画面传递检索用参数
		model.addAttribute("selPurchaseMaterial",selPurchaseMaterial);
		// 画面跳转
		return "modules/purchase/selPurchaseMaterial";
	}
	
	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param commonMaterialList
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws Exception
	 */
	@RequiresPermissions("purchase:request:view")
	@RequestMapping(value = { "searchMaterialList" })
	@ResponseBody
	public String searchMaterialList(SelPurchaseMaterial selPurchaseMaterial, HttpServletRequest request, HttpServletResponse response,
							 Model model) throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "selPurchaseMaterial");
		// 画面取得的检索项目
		// 供货商
		String venderId = selPurchaseMaterial.getVenderId();
 		// 采购合同号
		String contractMeterialNo = selPurchaseMaterial.getContractMeterialNo();
		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		searchParam.append("&venderId=");
		searchParam.append(venderId);
		searchParam.append("&contractMeterialNo=");
		searchParam.append(contractMeterialNo);
		searchParam.append("&contractStatus=");
		// 状态签订合同
		searchParam.append(ResourcesUtil.getConfig("purchase_status_20"));
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());
		// 查询一览页面数据
		selPurchaseMaterial.setContractStatus(ResourcesUtil.getConfig("purchase_status_20"));
		Page<SelPurchaseMaterial> page = selPurchaseMaterialService.findList(new Page<SelPurchaseMaterial>(request, response),
				selPurchaseMaterial);
		// 读取系统路径
		// 读取文件生成字符串
		String strUri = request.getContextPath() + Global.getAdminPath();
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		map.put("adminUri", strUri);
		map.put("materialList", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
		strHtml = FreeMarkerTemplateUtils
				.processTemplateIntoString(freemarkerConfiguration.getTemplate("selPurchaseMaterial.ftl"), map);
		listMap.put("selPurchaseMaterial", strHtml);
		listMap.put("page", page.getHtml());
		listMap.put("materialList", page.getList());
		// ajax返回结果
		return renderString(response, listMap);
	}
}
